package com.newsappserver.userservice.defines;

import com.newsappserver.userservice.dto.response.ApiResponse;
import org.springframework.dao.DataAccessException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

// 全局异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value ={ Exception.class})
    ResponseEntity<ApiResponse> handleException(Exception ex) {
        ErrorCode errorCode = ErrorCode.UNCATEGORIZED_EXCEPTION;
        String errorMessage = ex.getMessage();

        if (ex instanceof DataAccessException) {
            errorCode = ErrorCode.DATABASE_ERROR;
            errorMessage = "Database error";
        }

        ApiResponse apiResponseError = new ApiResponse();
        apiResponseError.setCode(errorCode.getCode());
        apiResponseError.setMessage(errorMessage);

        return ResponseEntity.status(errorCode.getCode()).body(apiResponseError);
    }


}
